package com.appkudos.view;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.appkudos.model.App;
import com.appkudos.model.Group;
import com.appkudos.model.User;
import com.appkudos.controller.GroupController;
import com.appkudos.controller.UserController;
import com.appkudos.view.R;
import android.app.Activity;
import android.os.Bundle;

import android.content.Intent;
import android.database.Cursor;
import android.provider.Browser;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.SimpleCursorAdapter;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class JoinGroupActivity extends Activity implements OnClickListener, ViewBinder{
    ListView lv;
    Button findButton;
    Cursor cur;
    TextView search_text;
    TextView search_help_text;
    EditText search_box;
	private Activity PARENTACTIVITY; 
	Group group;
	User user;
	UserController uc;
	ArrayList<Group> existing_groups;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_search);
        PARENTACTIVITY = this;
        
        // get user info
	    Intent launchIntent = getIntent();
	    Bundle extras = launchIntent.getExtras();
	    uc = new UserController();
	    user = uc.getCurrentUser(extras);
	    
	    // get all groups the user is in
	    existing_groups = (ArrayList<Group>) uc.getGroupsOfUser(user.getUsername());
        
        search_text = (TextView) this.findViewById(R.id.search_text);
        search_text.setText("Join Group");
        search_help_text = (TextView) this.findViewById(R.id.search_help_text);
        search_help_text.setText("Enter keyword or category");
        
        
//        // get bookmark from database (values are from tutorial example)
//        // create projection (define which columns to get)
//        String[] projection = new String[] {Browser.BookmarkColumns._ID, 
//        Browser.BookmarkColumns.TITLE, 
//        Browser.BookmarkColumns.URL,
//        Browser.BookmarkColumns.VISITS};
//        
//        // display title only
//        String[] displayFields = new String[] {
//        Browser.BookmarkColumns.TITLE};
//  	  
//        // get the int value of the textview field 
//        int[] displayViews = new int[] {R.id.add_button};
//        
//        // get information from database 
//  	    cur = managedQuery(android.provider.Browser.BOOKMARKS_URI, projection, null, null, null);
//  	   
  	    // get listview from layout
  	    lv=(ListView)findViewById(R.id.search_result);
		//lv.setVisibility(View.GONE);
		
  	    // open a new page when add friend is clicked
  	    findButton = (Button) this.findViewById(R.id.search_find_button);
        findButton.setOnClickListener(this);  	    // open a new page when add friend is clicked         
   }

	@Override
	public void onClick(View arg0) {
		
	      search_box = (EditText) this.findViewById(R.id.search_box);
	      String keyword = search_box.getText().toString();
//	      Toast.makeText(getApplicationContext(), "keyword is "+keyword,Toast.LENGTH_LONG).show();
	      
	      //TODO: uncomment searchForGroup
	      // get groups that matched the keyword
	      GroupController gc = new GroupController();
	      List<Group> matched_groups = gc.searchForGroup(keyword);
	      
//	      List<Group> matched_groups = new ArrayList<Group>();
//	      Group g1 = new Group("1", "cooking", "share cooking related apps");
//	      Group g2 = new Group("1", "photography", "sharing photos");
//	      Group g3 = new Group("1", "sports", "share sports related things...");
//	      
//	      matched_groups.add(g1);
//	      matched_groups.add(g2);
//	      matched_groups.add(g3);
	      
	      // display list of matched groups
	      if(matched_groups.size() == 0){ 
	    	  Toast.makeText(getApplicationContext(), "no matched groups",Toast.LENGTH_LONG).show();
	    	  lv.setVisibility(View.GONE);
	      }else{
	    	  displayMatchedGroups(matched_groups);
	    	  lv.setVisibility(View.VISIBLE);
	      }		
	}
	
	 private void displayMatchedGroups(List list){
	    	Map<String, Group> itemData;
	    	List<Map<String, Group>> listData = new ArrayList<Map<String, Group>>();
	    	
	    	// put the groups into a hashmap (used for input by simple adapter)
	    	for(int j=0; j<list.size();j++){
	    		itemData = new HashMap<String, Group>(1);
	    		group = (Group) list.get(j);
	    		itemData.put("add_button", group);
	    		listData.add(itemData);
	    	}    

	    	// bind simple adapter to the list view
	        SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData, R.layout.two_column_item,
	                new String[] {
	                    "add_button"
	                }, new int[] {
	                    R.id.add_button
	                });
	        
	        // bind viewBinder to adapter and set adapter to listview
	        simpleAdapter.setViewBinder(this);
	        lv.setAdapter(simpleAdapter);
	    }
	        
	 // check if the user is already friends with matched user
	  private boolean checkExistingGroup(Group matched){
		  boolean existed = false;
		  
		  for (int i=0; i<existing_groups.size();i++){
			  if(existing_groups.get(i).getGroupName().compareTo(matched.getGroupName()) == 0){
				  existed = true;
				  return existed;
			  }     
		  }
		  return existed;
	  }
	  
	    @Override
	    public boolean setViewValue(View view, Object data, String stringRepresetation) {  	
	    	// get data for the row
	    	Group group = (Group) data;
	        CheckedTextView ck = (CheckedTextView) view;
	        
	        // bind information to textView
	        ck.setText(group.getGroupName());
	        ck.setTag(group.getGroupID());
          	
	        if(checkExistingGroup(group)){
	        	ck.setChecked(true);
	        }else{
	        	ck.setChecked(false);
          	}

          	ck.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v)
               {
            	   CheckedTextView ckbox = (CheckedTextView) v;
            	   String grp = ckbox.getText().toString();
            	   String gid = (String) ckbox.getTag();
            	   
	   	           if(!ckbox.isChecked()){
	   	        	   ckbox.toggle();
	   	        	   uc.addUserToGroup(user.getUsername(),gid);
		   	           Toast.makeText(getApplicationContext(), "Successfully joined "+grp+" group",Toast.LENGTH_SHORT).show();
	   	           }else{
	   	        	   Toast.makeText(getApplicationContext(), "You are already a member of "+grp,Toast.LENGTH_SHORT).show();
	   	           }
               }
           });

	        return true;
	    }
}
